//
//  ECPrivateLetterDetailVc.m
//  Edu_iOS2018
//
//  Created by apple on 2018/1/12.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#import "ECPrivateLetterDetailVc.h"
#import "CellModelFrame.h"
#import "CellModel.h"
#import "ECMinePrivateLetterDetailCell.h"


@interface ECPrivateLetterDetailVc ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UITextField *messageTF;

@property (nonatomic, strong)NSMutableArray* cellModelFrame;

@property (nonatomic, strong) NSArray *tmpArray;

@end

@implementation ECPrivateLetterDetailVc

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.title = self.nickname;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.tableView];
    self.bottomView.backgroundColor = [UIColor colorWithHexString:@"#F1F0EB"];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardDidChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [self getDataWithURL];
    
}

/*  加载数据  */
-(void)getDataWithURL{
    DLog(@"%@",[[UserInfoManager shareUser] token]);;
    [HWHttpTool requestWithMethod:@"GET"
                              url:URL_GET_Mine_Messages_DetailWithId(self.ID)
                           params:@{@"limit":@"1000"}
                          headers:@{@"X-AUTH-TOKEN":[[UserInfoManager shareUser] token]}
                          success:^(id json) {
                              DLog(@"%@",json);
                              if ([json[@"code"] intValue] == 200) {
                                  
                                  NSArray *array = [[json[@"data"][@"resources"] reverseObjectEnumerator] allObjects];
                                  
                                  for (NSUInteger i = 0 ; i< array.count; i++) {//倒转数组
                                      CellModel* cellModel=[CellModel cellModelWithDict:array[i]];
                                      CellModelFrame* cellModelFrame=[[CellModelFrame alloc]init];
                                      cellModelFrame.cellModel=cellModel;
                                      [self.cellModelFrame addObject:cellModelFrame];
                                  }
                                  [self.tableView reloadData];
                                  
                                  NSIndexPath *indexpath = [NSIndexPath indexPathForRow:self.cellModelFrame.count-1 inSection:0];
                                  [self.tableView scrollToRowAtIndexPath:indexpath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                                  
                                  //[self scrollToBottom];
                              }else{
                                  [MBProgressHUD showTipMessageInWindow:json[@"message"]];
                              }
                          }
                          failure:^(NSError *error) {
                              NSString *str = [ECData_Json requestErrorTipWith:error];
                              DLog(@"%@",str);
                              if (!([str isEqualToString:@"101"] || [str isEqualToString:@"401"])) {
                                  [MBProgressHUD showTipMessageInWindow:@"数据请求失败"];
                              }
                          }];
}

/**  键盘通知  */
-(void)keyboardDidChangeFrame:(NSNotification*)noti{
    [UIApplication sharedApplication].keyWindow.backgroundColor=self.tableView.backgroundColor;
    CGRect frame=[noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat durationTime=[noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [UIView animateWithDuration:durationTime animations:^{
        //设置view的新frame
        self.view.transform=CGAffineTransformMakeTranslation(0, frame.origin.y-kScreenHeight);
    }];
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNavHeight, kScreenWidth, kScreenHeight-kNavHeight-kProportion_Height(135)-kSafeAreaBottomHeight) style:UITableViewStylePlain];
        self.tableView.backgroundColor=[UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = 0;
    }
    return _tableView;
}

-(UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]init];
        [self.view addSubview:_bottomView];
        WeakSelf(weakSelf);
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(weakSelf.view.mas_bottom).mas_offset(-kSafeAreaBottomHeight);
            make.width.equalTo(weakSelf.view.mas_width);
            make.height.equalTo(@(kProportion_Height(135)));
        }];
        
        _messageTF = [[UITextField alloc]init];
        [_bottomView addSubview:_messageTF];
        _messageTF.placeholder = @"请输入文本信息...";
        _messageTF.font = [UIFont systemFontOfSize:16.f];
        [_messageTF mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_bottomView.mas_centerY);
            make.height.equalTo(_bottomView.mas_height);
            make.left.equalTo(_bottomView.mas_left).offset(kProportion_Width(45));
            make.right.equalTo(_bottomView.mas_right).offset(-kProportion_Width(200));
        }];
        
        ECUButton *sendBtn = [ECUButton buttonWithType:UIButtonTypeCustom];
        [_bottomView addSubview:sendBtn];
        [sendBtn addTarget:self action:@selector(sendBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [sendBtn setBackgroundImage:[UIImage imageNamed:@"Mine_chatBottomPress"] forState:0];
        [sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_messageTF.mas_centerY);
            make.right.equalTo(_bottomView.mas_right).offset(-kProportion_Width(72));
            make.width.equalTo(@(kProportion_Width(74)));
            make.height.equalTo(sendBtn.mas_width).multipliedBy(67.f/74.f);
        }];
        
    }
    return _bottomView;
}

#pragma mark-tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cellModelFrame.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ECMinePrivateLetterDetailCell* cell=[ECMinePrivateLetterDetailCell tableViewCellWithTableView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ///cell.cellModelF = self.cellModelFrame[indexPath.row];

    if (indexPath.row == 0) {
        [cell setContentOfCellWith:self.cellModelFrame[indexPath.row] andLastModel:self.cellModelFrame[indexPath.row]];
    }else{
        [cell setContentOfCellWith:self.cellModelFrame[indexPath.row] andLastModel:self.cellModelFrame[indexPath.row-1]];
    }
    
    
    return cell;
}

#pragma mark-tableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self.cellModelFrame[indexPath.row] cellHight];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

#pragma mark-textFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    //清空输入框
    self.messageTF.text=@"";
    return YES;
}

#pragma mark 点击发送按钮后 进行处理
-(void)sendBtnClick{
    if ([self.messageTF.text isEqualToString:@""]) {
        return;
    }
    [self sendChatData];
}

/*  加载数据  */
-(void)sendChatData{
    DLog(@"%@",[[UserInfoManager shareUser] token]);
    [HWHttpTool requestWithMethod:@"POST"
                              url:URL_GET_Mine_Messages
                           params:@{@"nickname":self.nickname,
                                    @"content":self.messageTF.text
                                    }
                          headers:@{@"X-AUTH-TOKEN":[[UserInfoManager shareUser] token]}
                          success:^(id json) {
                              DLog(@"%@",json);
                              CellModel *newmodel = [[CellModel alloc]init];
                              newmodel.id = @"111";
                              newmodel.content = self.messageTF.text;
                              newmodel.type = @"me";
                              newmodel.smallAvatar = [[UserInfoManager shareUser]smallAvatar];
                              newmodel.createdTime = [self getCurrentTimes];
                              CellModelFrame* cellModelFrame=[[CellModelFrame alloc]init];
                              cellModelFrame.cellModel=newmodel;
                              [self.cellModelFrame addObject:cellModelFrame];
                              
                              //清空输入框
                              self.messageTF.text=@"";
                              
                              [self updateTableView];
                          }
                          failure:^(NSError *error) {
                              NSString *str = [ECData_Json requestErrorTipWith:error];
                              DLog(@"%@",str);
                              if (!([str isEqualToString:@"101"] || [str isEqualToString:@"401"])) {
                                  [MBProgressHUD showTipMessageInWindow:@"发送失败"];
                              }
                          }];
}

//更新界面
-(void)updateTableView{
    [self.tableView beginUpdates];
    NSIndexPath* path=[NSIndexPath indexPathForRow:self.cellModelFrame.count-1 inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

-(NSMutableArray *)cellModelFrame{
    if (_cellModelFrame==nil) {
        _cellModelFrame=[[NSMutableArray alloc]init];
    }
    return _cellModelFrame;
}

-(NSString*)getCurrentTimes{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // ---------设置格式,hh与HH的区别:分别表示12小时制,24小时制
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *datenow = [NSDate date];
    //----------将nsdate按formatter格式转成nsstring
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    DLog(@"currentTimeString =  %@",currentTimeString);
    return currentTimeString;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    CellModelFrame *lastModel = self.cellModelFrame.lastObject;
    if (self.block_back) {
        self.block_back(lastModel);
    }
}

//滚动到最底部
- (void)scrollToBottom{
    CGFloat yOffset = CGFLOAT_MAX; //设置要滚动的位置 0最顶部 CGFLOAT_MAX最底部
    if (self.tableView.contentSize.height > self.tableView.bounds.size.height) {
        yOffset = self.tableView.contentSize.height - self.tableView.bounds.size.height;
    }
    [self.tableView setContentOffset:CGPointMake(0, yOffset) animated:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
